package org.qydjk.console.controller.basic;


import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.Category;
import org.qydjk.common.pojo.SellerProductLabel;
import org.qydjk.common.pojo.SellerProductLabelDetail;
import org.qydjk.common.pojo.product.ProductLabelDetail;
import org.qydjk.common.pojo.seller.SellerLabelDetail;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.ListUtil;
import org.qydjk.common.util.RedisTemplateUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.Tree;
import org.qydjk.console.service.ICategoryService;
import org.qydjk.console.service.ISellerProductLabelDetailService;
import org.qydjk.console.service.ISellerProductLabelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 标签管理Controller
 * Created by Edward_yang on 2017/12/11 0011.
 */
@Controller
@RequestMapping("/label")
public class LabelController extends BaseController {
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private ISellerProductLabelService sellerProductLabelService; //标签Service
    @Autowired
    private ISellerProductLabelDetailService sellerProductLabelDetailService;//标签明细Service
    @Autowired
    private ICategoryService categoryService;//分类Service

    /***
     * 标签列表页跳转
     * @author Edward_yang
     * @uptime 2017-12-11
     * @return
     */
    @RequestMapping("/labelList.do")
    public String   LabelList(){


        return "basic/sellerAndproduct/labelList";
    }

    /***
     * 分类列表查询
     * @author Edward_yang
     * @uptime 2017-12-11
     */
    @RequestMapping("/classifylist.do")
    @ResponseBody
    public Object classifyList(Integer page, Integer rows){
        try {
            return categoryService.findAllCategoryList(page,rows);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /***
     * 分类下拉查询
     * @author Edward_yang
     * @uptime 2017-12-12
     */
    @RequestMapping("/classifyComboboxList.do")
    @ResponseBody
    public Object classifyComboboxList(){
        try {
            return categoryService.findAllList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /***
     * 标签列表查询
     * @author Edward_yang
     * @uptime 2017-12-11
     */
    @RequestMapping("/list.do")
    @ResponseBody
    public Object labelInfo(Integer page, Integer rows,String one_category_id,String keyWord,String type){
        try {
            return sellerProductLabelService.findLabelList(page,rows,one_category_id,keyWord,type);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /***
     * 标签下拉查询
     * @author Edward_yang
     * @uptime 2017-12-12
     */
    @RequestMapping("/labelComboboxList.do")
    @ResponseBody
    public Object labelComboboxList(String labelCatCode){
        try {
            return baseService.findByHql("from SellerProductLabel where code = ?",labelCatCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 标签明细列表查询
     * @author Edward_yang
     * @uptime 2017-12-12
     */
    @RequestMapping("/detail/list.do")
    @ResponseBody
    public Object labelDetailList(Integer page, Integer rows,String sellerProductLabelCode,String keyWord){
        try {
            return sellerProductLabelDetailService.findLabelDetailList(page,rows,sellerProductLabelCode,keyWord);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 标签添加
     * @author Edward_yang
     * @uptime 2017-12-11
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object addLabel(SellerProductLabel label){
        try {
            label.setCreateTime(new Date());//创建时间
            label.setUpdateTime(new Date());

            label = buildOneCatgoryId(label);

            baseService.save(label);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 标签修改
     * @author Edward_yang
     * @uptime 2017-12-11
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object editLabel(SellerProductLabel label){
        try {
            SellerProductLabel label1=baseService.get(SellerProductLabel.class,label.getId());
            BeanUtil.copyProperties(label,label1);
            label1.setUpdateTime(new Date());//修改时间

            label1 = buildOneCatgoryId(label1);

            baseService.saveOrUpdate(label1);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 根据分类ID获取顶级分类ID
     * @param label
     * @return
     * @throws Exception
     */
    private SellerProductLabel buildOneCatgoryId(SellerProductLabel label) throws Exception {
        Integer catId = label.getCategoryId();
        Category cat = baseService.get(Category.class, catId.intValue());
        String pids = cat.getParentIdAll();
        if(StringUtil.isEmptyOrNull(pids)){
            label.setOneCategoryId(0);
        }else{
            String[] ids = pids.split(",");
            label.setOneCategoryId(Integer.parseInt(ids[0]));
        }
        return label;
    }

    /***
     * 标签删除
     * @author Edward_yang
     * @uptime 2017-12-11
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object deleteLabel(Integer id){
        try {
            SellerProductLabel label= baseService.get(SellerProductLabel.class,id);
            String hqlCount="select count(spld.id) from SellerProductLabelDetail spld where spld.sellerProductLabelCode='"+label.getCode().toString()+"'";
            int total = baseService.getRecordCountHQL(hqlCount);
            if(total>0){
                return renderError("请删除该标签的明细");
            }else{
                baseService.delete(label);
                return renderSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 标签明细添加
     * @author Edward_yang
     * @uptime 2017-12-12
     */
    @RequestMapping("/detail/add.do")
    @ResponseBody
    public Object addLabelDetail(SellerProductLabelDetail sPLabelDetail){
        try {
            sPLabelDetail.setCreateTime(new Date());//创建时间
            sPLabelDetail.setUpdateTime(new Date());
            baseService.save(sPLabelDetail);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 标签修改
     * @author Edward_yang
     * @uptime 2017-12-12
     */
    @RequestMapping("/detail/edit.do")
    @ResponseBody
    public Object editLabelDetail(SellerProductLabelDetail sPLabelDetail){
        try {
            SellerProductLabelDetail sPLabelDetail1=baseService.get(SellerProductLabelDetail.class,sPLabelDetail.getId());
            BeanUtil.copyProperties(sPLabelDetail,sPLabelDetail1);
            sPLabelDetail1.setUpdateTime(new Date());//修改时间
            baseService.saveOrUpdate(sPLabelDetail1);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 标签删除
     * @author Edward_yang
     * @uptime 2017-12-12
     */
    @RequestMapping("/detail/delete.do")
    @ResponseBody
    public Object deleteLabelDetail(Integer id){
        try {
            SellerProductLabelDetail sellerProductLabelDetail=baseService.get(SellerProductLabelDetail.class,id);
            baseService.delete(sellerProductLabelDetail);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }

    }

    /**
     * 查询所有的菜单
     * sellerId=-1商家标签
     * productId=-1产品标签
     * root=-1，加跟节点，不传则不加
     */
    @RequestMapping("/allTree.do")
    @ResponseBody
    public Object allTree() throws Exception {
        try {
            int type = 0;
            String sellerId = request.getParameter("sellerId");
            String productId = request.getParameter("productId");
            if(!StringUtil.isEmptyOrNull(sellerId)){
                type = 0;
            }else if(StringUtil.isEmptyOrNull(productId)){
                type = 1;
            }else{
                return null;
            }

            List<Tree> trees = new ArrayList<Tree>();
            // 查询所有标签
            List<SellerProductLabel> sellerProductLabels = baseService.findByHql("from SellerProductLabel spl where spl.type = ? ORDER BY spl.ord",type);
            if (sellerProductLabels == null) {
                return trees;
            }
            String labelCodes = "";
            for (SellerProductLabel label:sellerProductLabels) {
                labelCodes += "'" + label.getCode() + "',";
            }
            if(!StringUtil.isEmptyOrNull(labelCodes)){
                labelCodes = labelCodes.substring(0,labelCodes.length() - 1);
            }
            // 查询所有标签的明细
            List<SellerProductLabelDetail> sellerProductLabelDetails = baseService.findByHql("from SellerProductLabelDetail spld where spld.sellerProductLabelCode in (" + labelCodes + ") ORDER BY spld.ord");



            boolean needRoot = true;
            String root = request.getParameter("root");
            if(StringUtil.isEmptyOrNull(root)){
                needRoot = false;
            }

            return buildLabelTree(sellerProductLabels,sellerProductLabelDetails,needRoot);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建标签树
     * @param sellerProductLabels
     * @param sellerProductLabelDetails
     * @param needRoot
     * @return
     */
    private List<Tree> buildLabelTree(List<SellerProductLabel> sellerProductLabels, List<SellerProductLabelDetail> sellerProductLabelDetails, boolean needRoot) {
        try {
            List<Tree> trees = new ArrayList<Tree>();
            for (SellerProductLabel label : sellerProductLabels) {
                int i = 0;
                for(SellerProductLabelDetail labelDetail : sellerProductLabelDetails){
                    if(label.getCode().equals(labelDetail.getSellerProductLabelCode())){
                        i++;
                        Tree tree = new Tree();
                        tree.setId(labelDetail.getId());
                        tree.setPid(label.getId());
                        tree.setText(labelDetail.getName());
                        tree.setAttributes(labelDetail.getCode());
                        trees.add(tree);
                    }
                }
                if(i > 0){
                    Tree tree = new Tree();
                    tree.setId(label.getId());
                    if(needRoot){
                        tree.setPid(-1);
                    }else{
                        tree.setPid(null);
                    }
                    tree.setText(label.getName());
                    tree.setAttributes(label.getCode());
                    trees.add(tree);
                }
            }
            if(needRoot){
                Tree tree = new Tree();
                tree.setId(-1);
                tree.setPid(null);
                tree.setText("根节点");
                trees.add(tree);
            }
            return trees;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 根据分类ID,构建标签表单
     */
    @RequestMapping("/buildLabelds.do")
    @ResponseBody
    public Object buildLabelds(String classifyIds,Integer sellerId,Integer productId){
        //0商家1产品
        int type = 0;
        try {
            //构建从子节点到父节点的所有分类ids
            String catIds = categoryService.findAllByLeafIds(classifyIds);
            if(StringUtil.isEmptyOrNull(catIds)){
                return renderError("分类错误");
            }

            //查询，商家和产品已配置项
            StringBuffer selectedCodesSb = new StringBuffer();
            if(sellerId != null){
                type = 0;
                if(sellerId.intValue() != -1){
                    List<SellerLabelDetail> list = baseService.findByHql("from SellerLabelDetail sld where sld.sellerId = ?", sellerId.intValue());
                    for(SellerLabelDetail sellerLabelDetail : list){
                        selectedCodesSb.append(sellerLabelDetail.getSellerProductLabelDetailCode()).append(",");
                    }
                }
            }else if(productId != null){
                type = 1;
                if(productId.intValue() != -1){
                    List<ProductLabelDetail> list = baseService.findByHql("from ProductLabelDetail sld where sld.productId = ?",productId.intValue());
                    for(ProductLabelDetail productLabelDetail : list){
                        selectedCodesSb.append(productLabelDetail.getSellerProductLabelDetailCode()).append(",");
                    }
                }
            }else{
                return renderError("参数错误");
            }

             List<SellerProductLabel> spls = baseService.findByHql("from SellerProductLabel spl where spl.type = " + type +" and spl.oneCategoryId in (" + catIds + ")");
             if(ListUtil.isNullOrEmpty(spls)){
                 return renderSuccess("");
             }
            String codes = "";
            for (SellerProductLabel spl: spls) {
                codes += "'" + spl.getCode() + "',";
            }
            codes = codes.endsWith(",") ? codes.substring(0,codes.length() - 1) : codes;
            List<SellerProductLabelDetail> splds = baseService.findByHql("from SellerProductLabelDetail spld where spld.sellerProductLabelCode in (" + codes + ") order by spld.ord desc");
            if(ListUtil.isNullOrEmpty(splds)){
                return renderSuccess("");
            }
            String res = buildLabelSelects(spls, splds,selectedCodesSb);
            return renderSuccess(res);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 构建标签select
     * @param spls 标签列表
     * @param splds 所有标签对应的所有标签明细列表
     * @param selectedCodesSb 已选择的标签codes，例如：000001,22222,00004
     * @return
     */
    private String buildLabelSelects(List<SellerProductLabel> spls,List<SellerProductLabelDetail> splds,StringBuffer selectedCodesSb){
        String selectedCodes = StringUtil.dotAddStartEnd(selectedCodesSb.toString());
        String selPrefix = "label_";
        StringBuffer sbRes = new StringBuffer("");
        for (int i = 0; i < spls.size(); i++) {
            StringBuffer sb = new StringBuffer("");
            int size = 0;
            SellerProductLabel spl = spls.get(i);
            String name = selPrefix + spl.getCode();
            SellerProductLabelDetail firstOption = null;
            boolean hasSelected = false;
            for (int j = 0; j < splds.size(); j++) {
                SellerProductLabelDetail spld = splds.get(j);
                if(spld.getSellerProductLabelCode().equals(spl.getCode())){
                    size++;
                    boolean contains = selectedCodes.contains(StringUtil.dotAddStartEnd(spld.getCode()));
                    if(j == 0){
                        if(contains){
                            hasSelected = true;
                            sb.append("<option selected value='" + spld.getCode() + "'>" +  spld.getName() + "</option>");
                        }else{
                            firstOption = spld;
                        }
                    }else if (contains){
                        hasSelected = true;
                        sb.append("<option selected value='" + spld.getCode() + "'>" +  spld.getName() + "</option>");
                    }else{
                        sb.append("<option value='" + spld.getCode() + "'>" +  spld.getName() + "</option>");
                    }
                }
            }
            //如果没有选中的，则添加第一个
            if(firstOption != null){
                if(hasSelected){
                    sb.insert(0,"<option value='" + firstOption.getCode() + "'>" +  firstOption.getName() + "</option>");
                }else{
                    //默认选择第一个
                    sb.insert(0,"<option selected value='" + firstOption.getCode() + "'>" +  firstOption.getName() + "</option>");
                }
            }
            sb.insert(0,spl.getName() + ":<select class='easyui-combobox' name='" + name + "' style='width: 300px; height: 29px;'>");
            sb.append("</select><br/><br/>");
            if(size > 0){
                sbRes.append(sb);
            }
        }
        return sbRes.toString();
    }

    /***
     * @author Edward_yang
     * @uptime 2018-01-04
     *初始化标签
     * @return
     */
    @RequestMapping("/initializeLabel.do")
    @ResponseBody
    public Object initializeLabel(){
        try {
            sellerProductLabelService.getLabelsToRedis(redisTemplateUtil);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }

    }

}
